﻿
using System.Diagnostics;

namespace TeachApplication2526A.CommonMiddleWare
{
    public class RequestLoggingMiddleware:IMiddleware
    {
        private readonly ILogger<RequestLoggingMiddleware> _logger;

        public RequestLoggingMiddleware( ILogger<RequestLoggingMiddleware> logger)
        {
            _logger = logger;
        }


        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            // 记录请求开始
            _logger.LogInformation("收到客户请求: {Method} {Path}", context.Request.Method, context.Request.Path);

            // 调用管道中的下一个中间件
            await next(context);

            stopwatch.Stop();

            // 记录请求完成
            _logger.LogInformation(
                "请求已处理： {Method} {Path} => 状态码：{StatusCode} in {ElapsedMilliseconds}毫秒",
                context.Request.Method,
                context.Request.Path,
                context.Response.StatusCode,
                stopwatch.ElapsedMilliseconds);

        }
    }
}
